<template>
	<view class="container">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<input type="text" placeholder="请输入搜索关键词" v-model="searchQuery" @confirm="onSearch" />
		</view>

		<!-- 布局容器 -->
		<view class="layout">
			<!-- 宠物类型列表（侧边栏） -->
			<view class="category-list">
				<view v-for="(type, index) in petTypes" :key="type.id"
					:class="['category-item', { active: activeType === index }]" @click="selectType(index)">
					{{ type.name }}
				</view>
			</view>

			<!-- 商品展示 -->
			<view class="product-list">
				<view v-for="(product, index) in products" :key="product.id" class="product-item card"
					@click="toProductDetails(product.id)">
					<image :src="product.img" class="product-image" />
					<view class="product-details">
						<text class="product-name">{{ product.name }}</text>
						<view class="product-prices">
							<view class="price-container">
								<text v-if="product.discount_price"
									class="product-discount-price">￥{{ product.discount_price }}</text>
								<text class="product-original-price"
									v-if="product.discount_price">￥{{ product.original_price }}</text>
								<text v-else class="product-original-price2">￥{{ product.original_price }}</text>
							</view>
							<view class="cart-container">
								<image src="/static/icon/zengjia-copy.png" class="icon-gouwuche"
									@click.stop="addToCart(product)"></image>
							</view>
						</view>
					</view>
				</view>
				<view class="no-more">没有更多啦</view>
			</view>
		</view>

		<!-- 对话框背景遮罩 -->
		<view v-if="isDialogVisible" class="mask" @click="closeDialog"></view>

		<!-- 对话框 -->
		<view v-if="isDialogVisible" class="dialog">
			<view class="dialog-content">
				<view class="product-info">
					<image :src="cartDialogProduct.img" class="product-image" />
					<view class="product-details">
						<text class="product-name">{{ cartDialogProduct.name }}</text>
						<view class="product-prices2">
							<text class="product-discount-price" v-if="cartDialogProduct.discount_price">￥{{ cartDialogProduct.discount_price }}</text>
							<text v-if="cartDialogProduct.discount_price" class="product-original-price">￥{{ cartDialogProduct.original_price }}</text>
							<text v-else class="product-original-price2">￥{{ cartDialogProduct.original_price }}</text>
						</view>
					</view>
				</view>
				<view>
					<text>请选择预约时间:</text>
						<view v-for="(dateGroup, index) in formattedSlots" :key="index">
						<text class="date-label">{{ formatDate(dateGroup[0].appointment_time) }}</text>
						<view class="time-slot">
							<view v-for="slot in dateGroup" :key="slot.id" @click="selectSlot(slot)"
								:class="{'time-option': true, 'selected': selectedSlot && selectedSlot.id === slot.id}">
								<text>{{ formatTime(slot.appointment_time) }}</text>
							</view>
						</view>
					</view>
				</view>
<!-- 				<view class="quantity-control">
					<button @click="decreaseQuantity">-</button>
					<view>{{ cartDialogProduct.quantity }}</view>
					<button @click="increaseQuantity">+</button>
				</view> -->
				<button @click="addProductToCart" class="add-to-cart-button">立即预约</button>
			</view>
		</view>
	</view>
</template>
<script>
export default {
  data() {
    return {
      searchQuery: '',
      petTypes: [],
      products: [],
      activeType: 0,
      isDialogVisible: false,
      cartDialogProduct: { quantity: 1 },
      availableSlots: [],
      selectedSlot: null,
    };
  },
  computed: {
    formattedSlots() {
      const slotsMap = this.availableSlots.reduce((acc, slot) => {
        const date = new Date(slot.appointment_time);
        const key = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
        if (!acc[key]) {
          acc[key] = [];
        }
        acc[key].push(slot);
        return acc;
      }, {});

      return Object.values(slotsMap);
    },
  },
  methods: {
    onSearch() {
      if (this.searchQuery.trim() !== '') {
        this.fetchProducts(this.searchQuery);
      }
    },
    fetchPetTypes() {
      uni.request({
        url: 'http://localhost:8887/Pettype/findAll',
        success: (res) => {
          if (res.data && res.data.data) {
            this.petTypes = res.data.data;
            this.selectType(0); // 加载第一个宠物类型的商品数据
          }
        },
        fail: () => {
          console.error('请求宠物类型数据失败');
          uni.showToast({
            title: '请求宠物类型数据失败',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    fetchProducts(name) {
      uni.request({
        url: `http://localhost:8887/Service/selectServicename?name=${encodeURIComponent(name)}`,
        success: (res) => {
          if (res.data && res.data.data && res.data.data.length > 0) {
            this.products = res.data.data;
          } else {
            this.products = [];
            uni.showToast({
              title: '没有找到相关商品',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: () => {
          console.error('请求商品数据失败');
          this.products = [];
          uni.showToast({
            title: '请求商品数据失败',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    selectType(index) {
      this.activeType = index;
      const type = this.petTypes[index];
      uni.request({
        url: `http://localhost:8887/Service/selectPettypeName?pettypeName=${encodeURIComponent(type.name)}`,      
        success: (res) => {
          if (res.data && res.data.data && res.data.data.length > 0) {
            this.products = res.data.data;
          } else {
            this.products = [];
            uni.showToast({
              title: '没有找到相关商品',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: () => {
          console.error('请求宠物类型商品数据失败');
          this.products = [];
          uni.showToast({
            title: '请求宠物类型商品数据失败',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    getAvailableSlots(service_id) {
      uni.request({
        url: `http://localhost:8887/Appointmentslot/selectservice_id?service_id=${service_id}`,
        success: (res) => {
          if (res.data && res.data.data) {
            this.availableSlots = res.data.data.filter(slot => slot.state === '可预约');
          }
        },
        fail: () => {
          console.error('请求预约时间段数据失败');
          uni.showToast({
            title: '请求预约时间段数据失败',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },
    addToCart(product) {
      this.getAvailableSlots(product.id); // 获取可预约的时间段
      this.cartDialogProduct = { ...product, quantity: 1 }; 
      this.isDialogVisible = true;
    },
    selectSlot(slot) {
      this.selectedSlot = slot;
    },
    increaseQuantity() {
      this.cartDialogProduct.quantity++;
    },
    decreaseQuantity() {
      if (this.cartDialogProduct.quantity > 1) {
        this.cartDialogProduct.quantity--;
      }
    },
    closeDialog() {
      this.isDialogVisible = false;
    },
    toProductDetails(productId) {
      uni.navigateTo({
        url: `/pages/servicedetail/servicedetail?id=${productId}`,
      });
    },
addProductToCart() {
    if (this.selectedSlot && this.cartDialogProduct) {
      // 构建传递给 servicesettlement 页面的参数
      const params = {
        service_id: this.cartDialogProduct.id,
        appointment_id: this.selectedSlot.id
      };
	console.log('124312:', params);
      // 跳转到 servicesettlement 页面，并传递参数
      uni.navigateTo({
        url: `/pages/servicesettlement/servicesettlement?product_id=${params.product_id}&appointment_id=${params.appointment_id}`,
      });
    } else {
      uni.showToast({
        title: '请选择商品和预约时间',
        icon: 'none',
        duration: 2000
      });
    }
  },
    formatDate(dateString) {
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },
    formatTime(dateString) {
      const date = new Date(dateString);
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
  },
  mounted() {
    this.fetchPetTypes();
  },
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  position: relative;
}
.search-bar {
  padding: 10px;
  background-color: #f8f8f8;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 100;
}
.search-bar input {
  flex-grow: 1;
  border: 1px solid #ddd;
  padding: 5px;
  border-radius: 4px;
}
.layout {
  display: flex;
  height: 100vh;
}
.category-list {
  width: 60px;
  background-color: #fff;
  position: sticky;
  top: 10px;
  z-index: 100;
  height: 100%;
}
.category-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
  text-align: center;
}
.category-item.active {
  background-color: #007aff;
  color: white;
}
.product-list {
  flex-grow: 1;
  background-color: #f8f8f8;
  padding: 10px;
  overflow-y: auto;
  padding-bottom: 200px;
}
.product-item {
  display: flex;
  align-items: flex-start;
  border: 1px solid #eee;
  border-radius: 8px;
  margin-bottom: 10px;
  padding: 10px;
  background-color: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}
.product-image {
  width: 150px;
  height: 90px;
}
.product-details {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 100%;
  height: 90px;
  padding-left: 10px;
}
.product-name {
  font-size: 16px;
  color: #333;
  font-weight: bold;
  width: 90%;
  display: inline-block;
  vertical-align: top;
  word-wrap: break-word;
  overflow: hidden;
  text-overflow: ellipsis;
}
.product-prices {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.price-container {
  flex-grow: 1;
}
.cart-container {
  display: flex;
  align-items: center;
}

.product-original-price2 {
  font-size: 18px;
  color: #e4393c;
  font-weight: bold;
}
.product-original-price {
  text-decoration: line-through;
  font-size: 14px;
  color: #999;
}
.product-discount-price {
  font-size: 18px;
  color: #e4393c;
  font-weight: bold;
}
.icon-gouwuche {
  width: 24px;
  height: 24px;
}
.mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}
.dialog {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  z-index: 1001;
}
.dialog-content {
  padding: 20px;
}
.product-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.quantity-control {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.quantity-control button {
  margin: 0 10px;
}
.add-to-cart-button {
  width: 100%;
  background-color: #e4393c;
  color: white;
  text-align: center;
  padding: 10px;
  border: none;
  outline: none;
  margin-top: 10px;
}
.no-more {
  width: 100%;
  text-align: center;
  margin-top: 20px;
  color: #999;
  font-size: 16px;
}
.date-label {
  font-weight: bold;
  margin-top: 10px;
  margin-bottom: 5px;
}
.time-slot {
  display: flex;
  flex-wrap: wrap;
  gap: 10px; /* Adjust the gap between time options */
}
.time-option {
  padding: 8px 12px;
  border: 1px solid #eee;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  background-color: #f0f0f0; /* Light background for better contrast */
}
.time-option.selected {
  background-color: #007aff;
  color: white;
}
.time-option:hover {
  background-color: #ebebeb;
}
</style>